const urlObj = myGetUrlVal();
console.log(urlObj);

setPage();

async function setPage() {
    const response = await myPromiseJQueryAjax('../server/goods_detail.php', 'post', { goods_id: urlObj.goods_id }, 'json');

    let mask = document.createElement('div');
    let glass = document.createElement('div');
    glass.classList.add('glass');
    mask.setAttribute('name', 'maskVisib');
    glass.setAttribute('name', 'glass');

    console.log(response);
    $('.container').html(`
        <div class="panel panel-default">
        <div class="panel-heading">
        <h3 class="panel-title">商品详细信息</h3>
        </div>
        <div class="panel-body">
        <div class="media">
            <div class="media-left">
            <a href="#" class="mask">
                <img class="media-object" src="${response.goods_big_logo}" alt="...">
            </a>
            </div>
            <div class="media-body">
            <h4 class="media-heading">${response.goods_name}</h4>
            <p>
                <i class="glyphicon glyphicon-yen"></i>
                <span>${response.goods_price}</span>
            </p>
            <div class="btn-group" role="group" aria-label="...">
                <button type="button" class="btn btn-default">XL</button>
                <button type="button" class="btn btn-default">L</button>
                <button type="button" class="btn btn-default">M</button>
                <button type="button" class="btn btn-default">S</button>
                <button type="button" class="btn btn-default">XS</button>
            </div>
            <p style="position:relative">
                <input name="num" value="1" class="num">
                <button name="-" type="button" class="jian btn btn-default">-</button>
                <button name="+" type="button" class="jia btn btn-default">+</button>
            </p>
            <p>
                <a href="javascript:;" class="btn btn-warning btn-lg" role="button">立即购买</a>
                <a href="JavaScript:;" name="cart" class="btn btn-danger btn-lg" role="button">加入购物车</a>
            </p>
            </div>
        </div>
        <ul class="nav nav-tabs">
            <li role="presentation" class="active"><a href="#">商品详细信息</a></li>
            <li role="presentation"><a href="#">商品参数信息</a></li>
            <li role="presentation"><a href="#">相关商品</a></li>
        </ul>
        <div>
            ${response.goods_introduce}
        </div>
        </div>
    </div>
    `)

    $('.media-left a').append(mask);
    $('.media').append(glass);

    $('.container').click(function (e) {
        if ($(e.target).attr('name') === '-') {
            let num = Number($('[name="num"]').val());

            num--;

            num = num < 1 ? 1 : num;

            $('[name="num"]').val(num);
        } else if ($(e.target).attr('name') === '+') {
            let num = Number($('[name="num"]').val());

            num++;

            num = num > response.goods_number ? response.goods_number : num;

            $('[name="num"]').val(num);
        } else if ($(e.target).attr('name') === 'cart') {
            const cookieObj = myGetCookie();

            console.log(cookieObj);
            if (cookieObj.login === undefined) {
                if (window.confirm('您还没有登录,点击确定跳转登录页面')) {
                    window.location.href = `../pages/login.html?url=${window.location.href}`
                }
            } else {
                let cart = localStorage.cart;

                if (cart === undefined) {
                    response.buy = true;

                    let num = Number($('[name="num"]').val());

                    if (!(num >= 1 && num <= response.goods_number)) {
                        window.alert(`您只能购买 1-${response.goods_number}范围内的商品`);
                        return;
                    }

                    response.num = num;

                    localStorage.cart = JSON.stringify([response])
                } else {
                    cart = JSON.parse(cart);
                    console.log(cart);

                    if (cart.length === 0) {
                        response.buy = true;
                        let num = Number($('[name="num"]').val());
                        if (!(num >= 1 && num <= response.goods_number)) {
                            window.alert(`您只能购买1-${response.goods_number}范围内的商品`);
                            return;
                        }
                        response.num = num;
                        cart.unshift(response);
                        localStorage.cart = JSON.stringify(cart);
                    } else {
                        // 查询 当前新增商品 在不在 购物车数组中
                        // 使用 数组.some() 判断 数组数据中 有没有 goods_id 和 当前商品 goods_id 相同的
                        // 如果 数组.some() 结果是 false 当前新增商品 不在 购物车数组中
                        // 如果 数组.some() 结果是 true  当前新增商品   在 购物车数组中
                        let bool = cart.some(function (item) {
                            return item.goods_id === response.goods_id;
                        })

                        if (bool === false) {
                            // 当前商品信息 直接 添加属性 写入 购物车数据信息中
                            // 新加入购物车的商品 默认 是 购买的状态 
                            response.buy = true;

                            let num = Number($('[name="num"]').val());

                            if (!(num >= 1 && num <= response.goods_number)) {
                                window.alert(`您只能购买1-${response.goods_number} 范围内的商品`);
                                return;
                            }

                            response.num = num;
                            // 在 cart 数组中 新增当前商品数据信息
                            // 使用 数组.unshift() 在 数组的起始位置新增当前商品
                            cart.unshift(response);

                            localStorage.cart = JSON.stringify(cart);
                        } else {
                            // 新增商品 在 购物车数组中 
                            // 找到 购物车数组中 相同商品 新增购买数量

                            for (let i = 0; i <= cart.length - 1; i++) {
                                if (cart[i].goods_id === response.goods_id) {
                                    let num = Number($('[name="num"]').val());
                                    if (cart[i].num + num > cart[i].goods_number) {
                                        window.alert(`您已经购买${cart[i].num}件商品,最多再买${cart[i].goods_number - cart[i].num}件商品`);
                                        return;
                                    }

                                    cart[i].num += num;
                                    localStorage.cart = JSON.stringify(cart)
                                    break;
                                }
                            }
                        }
                    }
                }
                window.location.href = '../pages/cart.html';
            }
        }
    })

    $('[class="mask"]').mouseenter(function () {
        mask.style.display = 'block';
        glass.style.display = 'block';
        glass.style.backgroundImage = `url("${response.goods_big_logo}")`;
    })

    $('[class="mask"]').mouseleave(function () {
        mask.style.display = 'none';
        glass.style.display = 'none';
    })

    $('[class="mask"]').mousemove(function (e) {
        

        let parentLeft = $('[class="mask"]').offset().left;
        let parentTop = $('[class="mask"]').offset().top;

        let imgWidth = $('[class="mask"]').width();
        let imgHeight = $('[class="mask"]').height();
        console.log(imgWidth );

        let maskWidth = parseInt($('[name="maskVisib"]').css('width'));
        let maskHeight = parseInt($('[name="maskVisib"]').css('height'));

        let x = e.pageX - parentLeft - maskWidth / 2;
        let y = e.pageY - parentTop - maskHeight / 2;
        
        x = x < 0 ? 0 : x;
        y = y < 0 ? 0 : y;
        
        x = x > imgWidth - maskWidth ? imgWidth - maskWidth : x;
        // console.log(maskWidth );
        y = y > imgHeight - maskHeight ? imgHeight - maskHeight : y;


        // log(x);
        // log(y);
        $('[name="maskVisib"]').css({ left: x + 'px' });
        $('[name="maskVisib"]').css({ top: y + 'px' });

        glass.style.backgroundPosition = `${-x * 4}px  ${-y * 4}px`;
    })
}